<?php

namespace api\zhengmaotong\controller;

use api\zhengmaotong\model\WalletModel;
use cmf\controller\RestBaseController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use think\facade\Request;

class WalletController extends RestBaseController
{
    // 充值功能
    public function addMoney()
    {
        $data = input('post.');
        $token = Request::header();

        if (!isset($token['token']) || empty($token['token'])) {
            $this->error('缺少token');
        }

        $key = new Key(config('app.jwt_key'), 'HS256');

        WalletModel::startTrans();

        try {
            $res = JWT::decode($token['token'], $key);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        $user_id = $res->data->user_id;

        // 获取充值金额
        $money = $data['money'];
        $reason = $data['reason'] ?? '充值';

        try {
            $newBalance = add_money($user_id, $money, $reason, 1);
            WalletModel::commit();
            return json(['status' => 'success', 'message' => '充值成功', 'new_balance' => $newBalance]);
        } catch (\Exception $e) {
            WalletModel::rollback();
            return json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }

    // 查询流水记录
    public function moneyRecord()
    {
        $token = Request::header();

        if (!isset($token['token']) || empty($token['token'])) {
            $this->error('缺少token');
        }

        $key = new Key(config('app.jwt_key'), 'HS256');

        try {
            $res = JWT::decode($token['token'], $key);
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }

        $user_id = $res->data->user_id;

        try {
            // 调用 common 函数查询流水记录
            $logs = record($user_id);

            return json(['status' => 'success', 'logs' => $logs]);
        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()], 500);
        }
    }
}